var express = require('express');
var router = express.Router();
let snowflake = require('node-snowflake').Snowflake;
const fileUtil = require('../utils/fileUtil');
const imageCompress = require('../utils/imageCompress');
let Busboy = require('busboy'),
  path = require('path'),
  fs = require('fs');
const basePath = path.join(__dirname, '..', '/public/');
const baseUrl = 'http://47.90.122.146:7001/';
const imagePath = '';

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

router.post('/upload', function (req, res, next) {
  let busboy = new Busboy({ headers: req.headers });
  let data = null;
  let staticUrlFormat = fileUtil.formatFilePath(imagePath);
  let fileArray = [];
  busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
    let suffix = path.extname(filename);
    let random = snowflake.nextId();
    let newFileName = random+suffix;
    fileArray.push(newFileName);    // 将图片名放入一个数组中
    let newFileUrl = staticUrlFormat+ newFileName;
    if(fileUtil.mkdir(newFileUrl)){
      const array = [];
      file.on('data', function(data) {
        array.push(data);
      });
      file.on('end', function() {
        imageCompress(basePath+newFileUrl, Buffer.concat(array)).then((result)=> {
          data = {
            'url': baseUrl+newFileUrl,
            'filename': filename,
            'mimetype': mimetype,
          };
          return res.json(data);
        }).catch((err)=> {

        });

      });
    }
  });
  busboy.on('finish', function () {

  });
  req.pipe(busboy);
});
module.exports = router;
